package ru.hh.team02.chat.messaging;

import java.util.HashMap;
import java.util.Set;

import ru.hh.team02.chat.client.Client;
import ru.hh.team02.chat.server.ChatServer;

/*
 * current version: personal queue per each client
 */
public class SendingService {
    private static final int WORKING_THREADS = 1; 
    
    private HashMap<String, SendingQueue> queues = 
            new HashMap<String, SendingQueue>();
    
    /*
     * given client name, add his personal queue
     */
    public void addQueue(String name) {
        synchronized (queues) {
            queues.put(name, new SendingQueue(WORKING_THREADS));
        }
    }
    
    /*
     * given client name, delete his personal queue
     */
    public void removeQueue(String name) {
        assert(queues.containsKey(name));
        synchronized (queues) {
            queues.remove(name);
        }
    }

    /**
     * Put the message for sending in the queue.
     * The addressee is already encapsulated inside the message.
     * @param message
     */
//    public static void sendMessage(Message message) {
//        sendingQueue.add(message);
//    }

    /**
     * Put message to all personal queues of people, 
     * who are in the same room as sender
     * @param text Message text
     * @param name Sender name
     */
    public void sendMessageToRoom(String text, String senderName) {
        String room = ChatServer.registry.getClientRoom(senderName);
        Set<Client> recepients = ChatServer.registry.getClientsFromRoom(room);

        for (Client recepient : recepients) {
            Message message = new Message(text, recepient);
            queues.get(recepient.getName()).add(message);
        }       
    }
}
